<template>
    <div class="main-container">
        <global />
        <div class="main-content">
            <div class="content-container">
                <el-tabs v-model="activeTab">
                        <div class="header">
                            <el-input v-model="searchQuery" placeholder="请输入学号/姓名" style="width: 200px;" />
                            <el-button type="primary" @click="Page">搜索</el-button>
                            <el-button type="primary" @click="handleBatchPsychEvaluation">心理评估</el-button>
                            <el-button type="success" @click="handleBatchStudyEvaluation">学习评估</el-button>
                            <el-button type="warning" @click="handleBatchSave">批量保存评估</el-button>
                        </div>

                        <!-- 编辑/新增学生成绩弹窗 -->
                        <el-dialog v-model="dialogVisible" title="添加成绩" width="40%">
                            <el-form-item label="学号">
                                <el-input v-model="stugrade.sgSid" placeholder="请输入学号" disabled></el-input>
                            </el-form-item>
                            <el-form-item label="综合成绩">
                                <el-input v-model="stugrade.sgGrades" placeholder="点击计算成绩按钮自动计算（效果评分和态度评分的平均分）"
                                    disabled></el-input>
                            </el-form-item>
                            <el-form-item label="综合评价">
                                <el-input v-model="stugrade.sgTappraise" placeholder="请输入评价"></el-input>
                            </el-form-item>
                            <el-form-item label="综合平时分">
                                <el-input v-model="stugrade.sgPgrades" placeholder="请输入综合平时分"></el-input>
                            </el-form-item>
                            <el-form-item label="学期">
                                <el-input v-model="stugrade.sgSemester" placeholder="请输入学期"></el-input>
                            </el-form-item>
                            <template #footer="scope">
                                <el-button @click="calculateComprehensiveGrade">计算综合成绩</el-button>
                                <el-button @click="dialogVisible = false">取消</el-button>
                                <el-button type="primary" @click="addgrade">确定</el-button>
                            </template>
                        </el-dialog>

                        <!-- 编辑/新增学生学习态度弹窗 -->
                        <el-dialog v-model="dialogVisible2" title="添加学习态度" width="40%">
                            <el-form-item label="姓名">
                                <el-input v-model="sattitude.saName" placeholder="请输入姓名"></el-input>
                            </el-form-item>
                            <el-form-item label="专业">
                                <el-select v-model="sattitude.saMajor" placeholder="请选择专业">
                                    <el-option v-for="major in majorOptions" :key="major" :label="major" :value="major" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="年级">
                                <el-select v-model="sattitude.saGrade" placeholder="请选择年级">
                                    <el-option v-for="grade in gradeOptions" :key="grade" :label="grade" :value="grade" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="描述">
                                <el-input v-model="sattitude.saAcontent" placeholder="请输入描述"></el-input>
                            </el-form-item>
                            <el-form-item label="评分">
                                <el-input v-model="sattitude.saScore" placeholder="请输入评分"></el-input>
                            </el-form-item>
                            <el-form-item label="计划">
                                <el-input v-model="sattitude.saPlan" placeholder="请输入计划"></el-input>
                            </el-form-item>
                            <template #footer="scope">
                                <el-button @click="dialogVisible2 = false">取消</el-button>
                                <el-button type="primary" @click="addsattitude">确定</el-button>
                            </template>
                        </el-dialog>
                        <!-- 编辑/新增学生学习效果弹窗 -->
                        <el-dialog v-model="dialogVisible3" title="添加学习效果" width="40%">
                            <el-form-item label="学号">
                                <el-input v-model="seffect.seSid" placeholder="请输入学号"></el-input>
                            </el-form-item>
                            <el-form-item label="效果描述">
                                <el-input v-model="seffect.seContent" placeholder="请输入效果描述"></el-input>
                            </el-form-item>
                            <el-form-item label="评分">
                                <el-input v-model="seffect.seScore" placeholder="请输入评分"></el-input>
                            </el-form-item>
                            <el-form-item label="建议">
                                <el-input v-model="seffect.seAdvice" placeholder="请输入建议"></el-input>
                            </el-form-item>
                            <template #footer="scope">
                                <el-button @click="dialogVisible3 = false">取消</el-button>
                                <el-button type="primary" @click="addseffect">确定</el-button>
                            </template>
                        </el-dialog>

                        <!-- 编辑/新增学生学习习惯弹窗 -->
                        <el-dialog v-model="dialogVisible4" title="添加习惯效果" width="40%">
                            <el-form-item label="学号">
                                <el-input v-model="shabit.shSid" placeholder="请输入学号"></el-input>
                            </el-form-item>
                            <el-form-item label="习惯描述">
                                <el-input v-model="shabit.shHcontent" placeholder="请输入习惯描述"></el-input>
                            </el-form-item>
                            <el-form-item label="频率">
                                <el-input v-model="shabit.shFrequency" placeholder="请输入频率"></el-input>
                            </el-form-item>
                            <el-form-item label="持续时间">
                                <el-input v-model="shabit.shDuration" placeholder="请输入持续时间"></el-input>
                            </el-form-item>
                            <template #footer="scope">
                                <el-button @click="dialogVisible4 = false">取消</el-button>
                                <el-button type="primary" @click="addshabit">确定</el-button>
                            </template>
                        </el-dialog>

                        <!-- 学生信息表格 -->
                        <el-table :data="studentList" border style="width: 100%; margin-top: 20px;"
                            @selection-change="handleSelectionChange" @expand-change="handleExpand">
                            <el-table-column type="expand">
                                <template #default="props">
                                    <div class="expand-detail">
                                        <!-- 详细评估信息 -->
                                        <el-tabs>
                                            <el-tab-pane label="学习态度">
                                                <div v-for="(item, index) in props.row.sattitudedtos" :key="index">
                                                    <el-descriptions :column="2" border>
                                                        <el-descriptions-item label="描述">{{ item.saAcontent
                                                            }}</el-descriptions-item>
                                                        <el-descriptions-item label="评分">{{ item.saScore
                                                            }}</el-descriptions-item>
                                                    </el-descriptions>
                                                </div>
                                            </el-tab-pane>
                                            <el-tab-pane label="学习效果">
                                                <div v-for="(item, index) in props.row.seffectdtos" :key="index">
                                                    <el-descriptions :column="2" border>
                                                        <el-descriptions-item label="描述">{{ item.seContent
                                                            }}</el-descriptions-item>
                                                        <el-descriptions-item label="评分">{{ item.seScore
                                                            }}</el-descriptions-item>
                                                    </el-descriptions>
                                                </div>
                                            </el-tab-pane>
                                            <el-tab-pane label="学习习惯">
                                                <div v-for="(item, index) in props.row.shabitdtos" :key="index">
                                                    <el-descriptions :column="2" border>
                                                        <el-descriptions-item label="描述">{{ item.shHcontent
                                                            }}</el-descriptions-item>
                                                        <el-descriptions-item label="频率">{{ item.shFrequency
                                                            }}</el-descriptions-item>
                                                        <el-descriptions-item label="开始时间">{{ item.shCreatetime
                                                            }}</el-descriptions-item>
                                                        <el-descriptions-item label="持续时间">{{ item.shDuration
                                                            }}</el-descriptions-item>
                                                    </el-descriptions>
                                                </div>
                                            </el-tab-pane>
                                        </el-tabs>

                                        <!-- 评估输入区域 -->
                                        <div class="evaluation-input">
                                            <h3>添加评估</h3>
                                            <el-form :model="getStudentForm(props.row.ssid)" label-width="100px">
                                                <el-row :gutter="20">
                                                    <el-col :span="8">
                                                        <el-form-item label="评估类型">
                                                            <el-select v-model="getStudentForm(props.row.ssid).type"
                                                                placeholder="请选择评估类型">
                                                                <el-option v-for="option in typeOptions"
                                                                    :key="option.value" :label="option.label"
                                                                    :value="option.value" />
                                                            </el-select>
                                                        </el-form-item>
                                                    </el-col>
                                                    <el-col :span="8">
                                                        <el-form-item label="评估得分">
                                                            <el-input-number
                                                                v-model="getStudentForm(props.row.ssid).score" :min="0"
                                                                :max="100" />
                                                        </el-form-item>
                                                    </el-col>
                                                    <el-col :span="8">
                                                        <el-form-item label="评估等级">
                                                            <el-select v-model="getStudentForm(props.row.ssid).level"
                                                                placeholder="请选择等级">
                                                                <el-option v-for="option in levelOptions"
                                                                    :key="option.value" :label="option.label"
                                                                    :value="option.value" />
                                                            </el-select>
                                                        </el-form-item>
                                                    </el-col>
                                                </el-row>
                                                <el-form-item label="评估内容">
                                                    <el-input type="textarea"
                                                        v-model="getStudentForm(props.row.ssid).content" rows="3" />
                                                </el-form-item>
                                                <el-form-item>
                                                    <el-button type="primary" @click="handleBatchSave">保存评估</el-button>
                                                </el-form-item>
                                            </el-form>
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column type="selection" width="55"></el-table-column>
                            <el-table-column prop="ssid" label="学号" />
                            <el-table-column prop="sname" label="姓名" />
                            <el-table-column prop="sgGrades" label="综合成绩" />
                            <el-table-column prop="sgSemester" label="学期信息" />
                            <el-table-column prop="sgTappraise" label="综合评价" />
                            <el-table-column prop="sgPgrades" label="综合表现分" />
                            <el-table-column label="操作" width="120">
                                <template #default="scope">
                                    <el-popover placement="right" :width="200" trigger="hover"
                                        popper-class="operation-popover">
                                        <template #reference>
                                            <el-button type="primary" plain>操作</el-button>
                                        </template>
                                        <div class="operation-buttons">
                                            <el-button type="warning" @click="handleAI(scope.row)">智能评估</el-button>
                                            <el-button type="warning" @click="handleGrade(scope.row)">添加成绩</el-button>
                                            <el-button 
                                                type="warning" 
                                                @click="handleEffect(scope.row)"
                                                :disabled="scope.row.seffectdtos && scope.row.seffectdtos.length > 0"
                                                :title="scope.row.seffectdtos && scope.row.seffectdtos.length > 0 ? '已有学习效果评价' : ''"
                                            >
                                                学习效果
                                            </el-button>
                                            <el-button 
                                                type="warning" 
                                                @click="seeshabit(scope.row)"
                                                :disabled="scope.row.shabitdtos && scope.row.shabitdtos.length > 0"
                                                :title="scope.row.shabitdtos && scope.row.shabitdtos.length > 0 ? '已有学习习惯评价' : ''"
                                            >
                                                学习习惯
                                            </el-button>
                                            <el-button 
                                                type="warning"
                                                @click="handleAttitude(scope.row)"
                                                :disabled="scope.row.sattitudedtos && scope.row.sattitudedtos.length > 0"
                                                :title="scope.row.sattitudedtos && scope.row.sattitudedtos.length > 0 ? '已有学习态度评价' : ''"
                                            >
                                                学习态度
                                            </el-button>
                                        </div>
                                    </el-popover>
                                </template>
                            </el-table-column>
                        </el-table>
                        <!-- 分页组件 -->
                        <div class="pagination-container">
                            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                                :page-sizes="[10, 20, 50, 100]" background
                                layout="total, sizes, prev, pager, next, jumper" :total="total" class="pagination"
                                @current-change="Page" />
                        </div>
                </el-tabs>
            </div>
        </div>
    </div>
</template>

<script>
import { reactive, toRefs, onMounted, ref, computed } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import axios from '@/router/axios'
import { getSessionStorage } from '@/router/common'

export default {
    setup() {
        const chartRef = ref(null);

        // 评估类型映射evaluationRecords
        const evaluationTypeMap = {
            1: '学习评估',
            2: '心理评估',
            4: '智能评估'
        };

        // 评估等级映射
        const evaluationLevelMap = {
            1: '正常',
            2: '良好',
            3: '关注',
            4: '预警'
        };

        const state = reactive({
            shabit:{
                shDuration:'',
                shFrequency:'',
                shHcontent:'',
                shSid: '',
                shTid: getSessionStorage("teacher").tTid,
            },
            stugrade: {
                sgGrades: '',
                sgTappraise: '',
                sgPgrades: '',
                sgSemester: '',
                sgSid: '',
                sgTid: '',
            },
            sattitude: {
                saName: '',
                saMajor: '',
                saGrade: '',
                saAcontent: '',
                saScore: '',
                saSource: getSessionStorage("teacher").tTid,
                saType: 1,
                saPlan: ''
            },
            seffect: {
                seSid: '',
                seContent: '',
                seScore: '',
                seAdvice: '',
                seTid: getSessionStorage("teacher").tTid,
            },
            mentalText: [],  // 改为空数组，我们会动态添加内容
            // 当前激活的标签页
            activeTab: 'info',

            // 搜索查询
            searchQuery: '',

            // 存储每个学生的表单数据
            evaluationForms: new Map(),

            // 存储每个学生的最新评估结果
            evaluationResults: new Map(),

            // 图表相关
            selectedStudent: '',
            selectedEvaluationType: '',

            // 分页相关
            currentPage: 1,
            pageSize: 10,
            total: 1000,

            // 年级和专业选项
            gradeOptions: [],
            majorOptions: [],

            // 模拟数据 - 学生列表
            studentList: [
                {
                    ssid: '202513001',
                    sname: '张三',
                    sgGrades: 85,
                    sgTappraise: '良好',
                    sgPgrades: 88,
                    smgrades: 600,
                    sattitudedtos: [
                        {
                            saAcontent: '课堂专注度高',
                            saScore: 90
                        },
                        {
                            saAcontent: '积极参与讨论',
                            saScore: 85
                        }
                    ],
                    seffectdtos: [
                        {
                            seContent: '理解能力强',
                            seScore: 88
                        }
                    ],
                    shabitdtos: [
                        {
                            shHcontent: '每日复习',
                            shFrequency: '每天',
                            shCreatetime: '2024-01-01',
                            shDuration: '2小时'
                        }
                    ]
                },
                {
                    ssid: '202513002',
                    sname: '李四',
                    sgGrades: 92,
                    sgTappraise: '优秀',
                    sgPgrades: 95,
                    smgrades: 650,
                    sattitudedtos: [
                        {
                            saAcontent: '学习态度认真',
                            saScore: 95
                        }
                    ],
                    seffectdtos: [
                        {
                            seContent: '成绩稳步提升',
                            seScore: 92
                        }
                    ],
                    shabitdtos: [
                        {
                            shHcontent: '提前预习',
                            shFrequency: '每周3次',
                            shCreatetime: '2024-01-15',
                            shDuration: '1.5小时'
                        }
                    ]
                }
            ],

            // 评估类型选项
            typeOptions: [
                { label: '学习评估', value: '1' },
                { label: '心理评估', value: '2' },
                { label: '智能评估', value: '4' },
            ],

            // 评估等级选项
            levelOptions: [
                { label: '正常', value: 1 },
                { label: '良好', value: 2 },
                { label: '关注', value: 3 },
                { label: '预警', value: 4 }
            ],
            dialogVisible: false,
            dialogVisible2: false,
            dialogVisible3: false,
            dialogVisible4: false,
        });

        function seeshabit(row) {
            state.dialogVisible4 = true;
            state.shabit.shSid = row.ssid;
        }
        function addshabit(){
            if(state.shabit.shSid == '' || state.shabit.shTid == '' || state.shabit.shHcontent == '' || 
            state.shabit.shFrequency == '' || state.shabit.shDuration == ''){
                ElMessage.warning('请填写完整');
                return;
            }
            axios.post('/api/teacher/tshabit/add', state.shabit).then(res => {
                const result = res.data;
                console.log(result);
                if (result.code == 1) {
                    ElMessage.success("添加成功");
                    state.dialogVisible4 = false;
                    state.shabit.shHcontent = '';
                    state.shabit.shFrequency = '';
                    state.shabit.shDuration = '';
                    state.shabit.shSid = '';
                    Page();
                } else {
                    ElMessage.error("添加失败");
                }
            })
        }


        function getstugrade() {
            console.log(state.stugrade)
            axios.get('/api/teacher/tscgrades/getstugradebyid', {
                params: {
                    scgSid: state.stugrade.sgSid,
                    scgSemester: state.stugrade.sgSemester
                }
            }).then(res => {
                const result = res.data;
                console.log(result);
                if (result.code == 1) {
                    state.stugrade.sgGrades = result.data.avgGrade;
                    state.stugrade.sgPgrades = result.data.avgPgrade;
                    ElMessage.success("成绩计算成功");
                }
            })
        }

        // 计算综合成绩（效果评分和态度评分的平均分）
        function calculateComprehensiveGrade() {
            if (!state.stugrade.sgSid) {
                ElMessage.warning('请先选择学生');
                return;
            }

            // 获取当前学生的数据
            const currentStudent = state.studentList.find(student => student.ssid === state.stugrade.sgSid);
            if (!currentStudent) {
                ElMessage.error('未找到学生信息');
                return;
            }

            let attitudeScores = [];
            let effectScores = [];

            // 获取学习态度评分
            if (currentStudent.sattitudedtos && currentStudent.sattitudedtos.length > 0) {
                attitudeScores = currentStudent.sattitudedtos
                    .map(item => parseFloat(item.saScore))
                    .filter(score => !isNaN(score) && score > 0);
            }

            // 获取学习效果评分
            if (currentStudent.seffectdtos && currentStudent.seffectdtos.length > 0) {
                effectScores = currentStudent.seffectdtos
                    .map(item => parseFloat(item.seScore))
                    .filter(score => !isNaN(score) && score > 0);
            }

            // 如果两个评分都没有有效数据
            if (attitudeScores.length === 0 && effectScores.length === 0) {
                ElMessage.warning('请先补全学习态度和学习效果评分');
                return;
            }

            // 计算平均分
            const attitudeAvg = attitudeScores.length > 0 ? 
                attitudeScores.reduce((sum, score) => sum + score, 0) / attitudeScores.length : 0;
            const effectAvg = effectScores.length > 0 ? 
                effectScores.reduce((sum, score) => sum + score, 0) / effectScores.length : 0;

            // 计算综合成绩（态度评分和效果评分的平均分）
            let comprehensiveGrade = 0;
            if (attitudeAvg > 0 && effectAvg > 0) {
                comprehensiveGrade = (attitudeAvg + effectAvg) / 2;
            } else if (attitudeAvg > 0) {
                comprehensiveGrade = attitudeAvg;
            } else if (effectAvg > 0) {
                comprehensiveGrade = effectAvg;
            }

            // 更新综合成绩
            state.stugrade.sgGrades = comprehensiveGrade.toFixed(1);

            // 显示计算详情
            let message = '综合成绩计算完成：\n';
            if (attitudeScores.length > 0) {
                message += `学习态度评分：${attitudeScores.join(', ')} (平均：${attitudeAvg.toFixed(1)})\n`;
            } else {
                message += '学习态度评分：暂无数据\n';
            }
            if (effectScores.length > 0) {
                message += `学习效果评分：${effectScores.join(', ')} (平均：${effectAvg.toFixed(1)})\n`;
            } else {
                message += '学习效果评分：暂无数据\n';
            }
            message += `综合成绩：${state.stugrade.sgGrades}`;

            ElMessage.success(message);
        }

        function Page() {
            axios.get('/api/teacher/assess/stupage', {
                params: {
                    page: state.currentPage,
                    pageSize: state.pageSize,
                    SSid: state.searchQuery
                }
            }).then(res => {
                const result = res.data;
                console.log(result);
                if (result.code == 1) {
                    state.studentList = result.data.records;
                    state.total = result.data.total;
                } else {
                    ElMessage.error("获取学生列表失败");
                }
            })
        }

        // 表格选择事件处理
        function handleSelectionChange(selection) {
            state.multipleSelection = selection;
            console.log('当前选中的学生:', state.multipleSelection);
        }

        // 获取或创建学生的表单数据
        function getStudentForm(ssid) {
            if (!state.evaluationForms.has(ssid)) {
                state.evaluationForms.set(ssid, {
                    type: '',
                    score: 0,
                    level: '',
                    content: ''
                });
            }
            return state.evaluationForms.get(ssid);
        }

        // 获取评估类型显示文本
        function getTypeText(type) {
            return evaluationTypeMap[type] || '';
        }

        // 获取评估等级显示文本
        function getLevelText(level) {
            if (level == 4) {
                return '预警';
            } else if (level == 3) {
                return '关注';
            } else if (level == 2) {
                return '良好';
            } else if (level == 1) {
                return '正常';
            }
        }

        // 检查学生信息完整性
        function checkStudentInfoComplete(student) {
            const missingInfo = [];
            
            // 检查成绩信息
            if (!student.sgGrades || student.sgGrades === '') {
                missingInfo.push('成绩信息');
            }
            
            // 检查学习态度评价
            if (!student.sattitudedtos || student.sattitudedtos.length === 0) {
                missingInfo.push('学习态度评价');
            }
            
            // 检查学习习惯评价
            if (!student.shabitdtos || student.shabitdtos.length === 0) {
                missingInfo.push('学习习惯评价');
            }
            
            // 检查学习效果评价
            if (!student.seffectdtos || student.seffectdtos.length === 0) {
                missingInfo.push('学习效果评价');
            }
            
            return {
                isComplete: missingInfo.length === 0,
                missingInfo: missingInfo
            };
        }

        // 批量学习评估处理方法
        function handleBatchStudyEvaluation() {
            if (state.multipleSelection.length === 0) {
                ElMessage.warning('请先选择要评估的学生');
                return;
            }
            
            // 检查所有选中学生的信息完整性
            const incompleteStudents = [];
            state.multipleSelection.forEach(student => {
                const checkResult = checkStudentInfoComplete(student);
                if (!checkResult.isComplete) {
                    incompleteStudents.push({
                        name: student.sname,
                        missingInfo: checkResult.missingInfo
                    });
                }
            });
            
            if (incompleteStudents.length > 0) {
                let message = '以下学生信息不完整，请先补全：\n';
                incompleteStudents.forEach(item => {
                    message += `${item.name}：缺少 ${item.missingInfo.join('、')}\n`;
                });
                ElMessage.warning(message);
                return;
            }
            
            ElMessage.info('开始批量学习评估');
            axios.post('/api/evaluation/learn', state.multipleSelection).then(res => {
                const result = res.data;
                if (result.code == 1) {
                    ElMessage.success("学习评估成功");
                    // 处理评估结果
                    result.data.forEach(evaluation => {
                        // 将评估结果存储到对应学生的数据中
                        state.evaluationResults.set(evaluation.ssid, {
                            type: '1', // 学习评估类型为1
                            typeText: '学习评估',
                            score: evaluation.tsScore,
                            level: evaluation.tsLevel,
                            levelText: getLevelText(evaluation.tsLevel),
                            content: evaluation.tsContent
                        });
                        // 更新该学生的表单数据
                        const form = getStudentForm(evaluation.ssid);
                        form.type = '1';
                        form.typeText = '学习评估';
                        form.score = evaluation.tsScore;
                        form.level = evaluation.tsLevel;
                        form.levelText = getLevelText(evaluation.tsLevel);
                        form.content = evaluation.tsContent;
                    });
                } else {
                    ElMessage.error("学习评估失败");
                }
            })
        }

        // 智能评估处理
        function handleAI(row) {
            deepseek(row);
        }

        // 修改展开行的处理方法
        function handleExpand(row) {
            const form = getStudentForm(row.ssid);
            // 如果该学生有评估结果，则显示结果
            if (state.evaluationResults.has(row.ssid)) {
                const result = state.evaluationResults.get(row.ssid);
                form.type = result.type;
                form.score = result.score;
                form.level = result.level;
                form.levelText = result.levelText;
                form.content = result.content;
            }
        }

        // 评估保存
        function saveEvaluation(student) {
            const form = getStudentForm(student.ssid);
            console.log('保存评估:', student.ssid, form);
            ElMessage.success('评估保存成功');
            // 重置表单
            form.type = '';
            form.score = 0;
            form.level = '';
            form.levelText = '';
            form.content = '';
        }

        // 批量心理评估处理方法
        function handleBatchPsychEvaluation() {
            if (state.multipleSelection.length === 0) {
                ElMessage.warning('请先选择要评估的学生');
                return;
            }
            
            // 检查所有选中学生的信息完整性
            const incompleteStudents = [];
            state.multipleSelection.forEach(student => {
                const checkResult = checkStudentInfoComplete(student);
                if (!checkResult.isComplete) {
                    incompleteStudents.push({
                        name: student.sname,
                        missingInfo: checkResult.missingInfo
                    });
                }
            });
            
            if (incompleteStudents.length > 0) {
                let message = '以下学生信息不完整，请先补全：\n';
                incompleteStudents.forEach(item => {
                    message += `${item.name}：缺少 ${item.missingInfo.join('、')}\n`;
                });
                ElMessage.warning(message);
                return;
            }
            
            // 改为 let，因为需要修改
            ElMessage.info('开始批量心理评估');
            console.log(state.multipleSelection);
            // 清空之前的数据
            state.mentalText = [];

            for (let i = 0; i < state.multipleSelection.length; i++) {
                const student = state.multipleSelection[i];
                let text = "";

                text += `\n学生综合信息：\n`;

                // 学习态度信息
                if (student.sattitudedtos && student.sattitudedtos.length > 0) {
                    text += "\n【学习态度】\n";
                    student.sattitudedtos.forEach((item, index) => {
                        if (item.saAcontent) {
                            text += `${index + 1}. ${item.saAcontent}\n`;
                        }
                    });
                }

                // 学习效果信息
                if (student.seffectdtos && student.seffectdtos.length > 0) {
                    text += "\n【学习效果】\n";
                    student.seffectdtos.forEach((item, index) => {
                        if (item.seContent) {
                            text += `${index + 1}. ${item.seContent}\n`;
                        }
                    });
                }

                // 学习习惯信息
                if (student.shabitdtos && student.shabitdtos.length > 0) {
                    text += "\n【学习习惯】\n";
                    student.shabitdtos.forEach((item, index) => {
                        if (item.shHcontent) {
                            text += `${index + 1}. ${item.shHcontent}\n`;
                        }
                    });
                }

                // 教师评价信息
                if (student.sgTappraise) {
                    text += "\n【教师评价】\n" + student.sgTappraise + "\n";
                }

                text += "\n----------------------------------------\n";

                // 将当前学生的信息添加到数组中
                state.mentalText.push({
                    text: text,
                    ssid: student.ssid,
                });
            }
            console.log(state.mentalText);
            axios.post('/api/evaluation/mental', state.mentalText).then(res => {
                const result = res.data;
                console.log(result);
                if (result.code == 1) {
                    ElMessage.success("心理评估成功");
                    // 处理评估结果
                    result.data.forEach(evaluation => {
                        // 将评估结果存储到对应学生的数据中
                        state.evaluationResults.set(evaluation.ssid, {
                            type: '2', // 学习评估类型为1
                            typeText: '心理评估',
                            score: evaluation.tsScore,
                            level: evaluation.tsLevel,
                            levelText: getLevelText(evaluation.tsLevel),
                            content: evaluation.tsScore == 0 ? '心理状态正常，继续保持！' : evaluation.tsContent
                        });
                        console.log(state.evaluationResults)
                        // 更新该学生的表单数据
                        const form = getStudentForm(evaluation.ssid);
                        form.type = '2';
                        form.typeText = '心理评估';
                        form.score = evaluation.tsScore;
                        form.level = evaluation.tsLevel;
                        form.levelText = getLevelText(evaluation.tsLevel);
                        form.content = evaluation.tsContent;
                    });
                } else {
                    ElMessage.error("心理评估失败");
                }
            })
        }

        function handleGrade(row) {
            state.dialogVisible = true;
            state.stugrade.sgSid = row.ssid;
            state.stugrade.sgTid = '';
            
            // 自动生成学期信息
            const now = new Date();
            const year = now.getFullYear();
            const month = now.getMonth() + 1; // 月份从0开始，需要+1
            
            let semester = '';
            if (month >= 2 && month <= 7) {
                // 春季学期：2月-7月
                semester = `${year}年春季期`;
            } else {
                // 秋季学期：8月-次年1月
                semester = `${year}年秋季期`;
            }
            
            state.stugrade.sgSemester = semester;
            state.stugrade.sgTappraise = '';
            state.stugrade.sgPgrades = '';
            state.stugrade.sgGrades = '';
        }

        function handleEffect(row) {
            state.dialogVisible3 = true;
            state.seffect.seSid = row.ssid;
            state.seffect.seContent = '';
            state.seffect.seScore = '';
            state.seffect.seAdvice = '';
        }
        function addseffect() {
            if(state.seffect.seSid == '' || state.seffect.seContent == '' || state.seffect.seScore == '' || state.seffect.seAdvice == ''){
                ElMessage.warning('请填写完整');
                return;
            }
            axios.post('/api/teacher/seffect/add', state.seffect).then(res => {
                const result = res.data;
                console.log(result);
                if (result.code == 1) {
                    ElMessage.success("学习效果添加成功");
                    state.dialogVisible3 = false;
                    Page();
                } else {
                    ElMessage.error(result.msg);
                }
            })
        }

        function handleAttitude(row) {
            state.dialogVisible2 = true;
            state.sattitude.saName = row.sname;
            state.sattitude.saMajor = '';
            state.sattitude.saGrade = '';
            state.sattitude.saAcontent = '';
            state.sattitude.saScore = '';
            state.sattitude.saPlan = '';
        }
        function addsattitude() {
            if(state.sattitude.saName == '' || state.sattitude.saMajor == '' || state.sattitude.saGrade == ''
             || state.sattitude.saAcontent == '' || state.sattitude.saScore == '' || state.sattitude.saPlan == ''){
                ElMessage.warning('请填写完整');
                return;
            }
            console.log(state.sattitude)
            axios.post('/api/attitude/add', state.sattitude).then(res => {
                const result = res.data;
                console.log(result);
                if (result.code == 1) {
                    ElMessage.success("学习态度添加成功");
                    state.dialogVisible2 = false;
                    Page();
                } else {
                    ElMessage.error(result.msg);
                }
            })
        }

        function deepseek(row) {
            // 检查学生信息完整性
            const checkResult = checkStudentInfoComplete(row);
            if (!checkResult.isComplete) {
                let message = `${row.sname} 信息不完整，请先补全：\n缺少 ${checkResult.missingInfo.join('、')}`;
                ElMessage.warning(message);
                return;
            }
            
            // 改为 let，因为需要修改
            ElMessage.info('开始智能评估');
            console.log(row);
            // 清空之前的数据
            state.mentalText = [];

            let text = "";
            const student = row;

            text += `\n学生综合信息：\n`;

            // 学习态度信息
            if (student.sattitudedtos && student.sattitudedtos.length > 0) {
                text += "\n【学习态度】\n";
                student.sattitudedtos.forEach((item, index) => {
                    if (item.saAcontent) {
                        text += `${index + 1}. ${item.saAcontent}\n`;
                    }
                });
            }

            // 学习效果信息
            if (student.seffectdtos && student.seffectdtos.length > 0) {
                text += "\n【学习效果】\n";
                student.seffectdtos.forEach((item, index) => {
                    if (item.seContent) {
                        text += `${index + 1}. ${item.seContent}\n`;
                    }
                });
            }

            // 学习习惯信息
            if (student.shabitdtos && student.shabitdtos.length > 0) {
                text += "\n【学习习惯】\n";
                student.shabitdtos.forEach((item, index) => {
                    if (item.shHcontent) {
                        text += `${index + 1}. ${item.shHcontent}\n`;
                    }
                });
            }

            // 教师评价信息
            if (student.sgTappraise) {
                text += "\n【教师评价】\n" + student.sgTappraise + "\n";
            }

            text += "\n----------------------------------------\n";

            // 将当前学生的信息添加到数组中
            state.mentalText.push({
                text: text,
                ssid: student.ssid,
            });

            axios.post('/api/deepseek/getDeepSeekResponse', state.mentalText[0]).then(res => {
                const result = res.data;
                console.log(result);
                if (result.code == 1) {
                    ElMessage.success("智能评估成功");
                    // 处理评估结果
                    result.data.forEach(evaluation => {
                        // 将评估结果存储到对应学生的数据中
                        state.evaluationResults.set(evaluation.ssid, {
                            type: '4', // 学习评估类型为1
                            typeText: '智能评估',
                            score: evaluation.tsScore,
                            level: evaluation.tsLevel,
                            levelText: getLevelText(evaluation.tsLevel),
                            content: evaluation.tsContent
                        });
                        console.log(state.evaluationResults)
                        // 更新该学生的表单数据
                        const form = getStudentForm(evaluation.ssid);
                        form.type = '4';
                        form.typeText = '智能评估';
                        form.score = evaluation.tsScore;
                        form.level = evaluation.tsLevel;
                        form.levelText = getLevelText(evaluation.tsLevel);
                        form.content = evaluation.tsContent;
                    });
                } else {
                    ElMessage.error("智能评估失败");
                }
            })
        }

        // 批量保存评估结果
        function handleBatchSave() {
            if (state.multipleSelection.length === 0) {
                ElMessage.warning('请先选择要保存评估的学生');
                return;
            }

            // 构建评估结果数组
            const evaluationResults = state.multipleSelection.map(student => {
                const form = getStudentForm(student.ssid);
                return {
                    tsContent: form.content || "未获取该学生综合信息，无法进行评估",  // 设置默认内容
                    tsId: 0,
                    tsLevel: form.level || "2",  // 设置默认等级为2
                    tsScore: form.score || 7,    // 设置默认分数为8
                    tsSid: student.ssid,
                    tsTid: getSessionStorage("teacher").tTid,
                    tsType: form.type || "3"
                };
            });
            let data = [];
            for (let i = 0; i < evaluationResults.length; i++) {
                let text = "";
                const content = evaluationResults[i].tsContent;
                console.log(content)
                // 判断 content 类型并处理
                if (typeof content === 'string') {
                    // 如果是字符串，直接赋值
                    text = content;
                } else if (Array.isArray(content)) {
                    // 如果是数组，将每个元素转为字符串并拼接
                    for (let j = 0; j < content.length; j++) {
                        console.log(content[j]);
                        text += content[j];
                    }
                }
                console.log(text)
                data.push({
                    tsContent: text,
                    tsId: evaluationResults[i].tsId,
                    tsLevel: evaluationResults[i].tsLevel,
                    tsScore: evaluationResults[i].tsScore,
                    tsSid: evaluationResults[i].tsSid,
                    tsTid: evaluationResults[i].tsTid,
                    tsType: evaluationResults[i].tsType
                });
            }
            console.log(data)

            axios.post('/api/teacher/assess/save', data).then(res => {
                const result = res.data;
                console.log(result);
                if (result.code == 1) {
                    ElMessage.success("评估结果已保存");
                    // 重置表单和相关状态
                    state.evaluationResults = new Map(); // 清空评估结果
                    state.multipleSelection = []; // 清空选中项
                    state.mentalText = []; // 清空心理评估文本

                    // 重新加载学生列表
                    Page();
                } else {
                    ElMessage.error("评估结果保存失败");
                }
            })
        }

        // 初始化图表
        onMounted(() => {
            if (chartRef.value) {
                const chart = echarts.init(chartRef.value);

                // 模拟评估趋势数据
                const option = {
                    title: {
                        text: '学生评估趋势'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    xAxis: {
                        type: 'category',
                        data: ['1月', '2月', '3月', '4月', '5月', '6月']
                    },
                    yAxis: {
                        type: 'value',
                        max: 100
                    },
                    series: [
                        {
                            name: '评估得分',
                            type: 'line',
                            data: [85, 87, 84, 91, 90, 93],
                            markLine: {
                                data: [{ type: 'average', name: '平均值' }]
                            }
                        }
                    ]
                };

                chart.setOption(option);
            }
            
            // 获取年级和专业数据
            getGradeAndM();
        });
        function addgrade() {
            if(state.stugrade.sgSemester == '' || 
            state.stugrade.sgGrades == '' || state.stugrade.sgPgrades == '' || state.stugrade.sgTappraise == ''   ){
                ElMessage.warning('请填写完整');
                return;
            }
            state.stugrade.sgTid = getSessionStorage("teacher").tTid;
            console.log(state.stugrade)
            axios.post('/api/teacher/grades/addstuGrades', state.stugrade).then(res => {
                const result = res.data;
                console.log(result);
                if (result.code == 1) {
                    ElMessage.success("成绩添加成功");
                    state.dialogVisible = false;
                    Page();
                } else {
                    ElMessage.error(result.msg);
                }
            })
        }

        // 获取年级和专业数据
        function getGradeAndM() {
            axios.get('api/teacher/student/getGradeAndSpecialty').then(res => {
                const result = res.data;
                console.log(result)
                if (result.code == 1) {
                    state.gradeOptions = result.data.grade;
                    state.majorOptions = result.data.major;
                } else {
                    ElMessage.error(result.msg);
                }
            })
        }

        Page();
        return {
            ...toRefs(state),
            chartRef,
            getstugrade,
            calculateComprehensiveGrade,
            checkStudentInfoComplete,
            saveEvaluation,
            handleBatchPsychEvaluation,
            handleBatchStudyEvaluation,
            handleAI,
            handleSelectionChange,
            handleExpand,
            getStudentForm,
            getTypeText,
            getLevelText,
            Page,
            handleBatchSave,
            deepseek,
            handleGrade,
            handleEffect,
            handleAttitude,
            addgrade,
            addsattitude,
            addseffect,
            seeshabit,
            addshabit,
            getGradeAndM,
        };
    }
};
</script>

<style scoped>
.main-container {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
}

.main-content {
    margin-left: 220px;
    margin-top: 60px;
    width: calc(100% - 220px);
    height: calc(100vh - 60px);
    overflow: auto;
}

.content-container {
    padding: 20px;
    min-height: calc(100% - 40px);
}

.header {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}

.expand-detail {
    padding: 20px;
}

.evaluation-input {
    margin-top: 20px;
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 4px;
}

.evaluation-input h3 {
    margin-bottom: 20px;
    color: #409EFF;
}

.chart-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-filters {
    margin-bottom: 20px;
}

.chart {
    height: 400px;
    width: 100%;
}

/* 响应式布局 */
@media (max-width: 768px) {
    .main-content {
        margin-left: 0;
        width: 100%;
    }
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
}

.operation-buttons {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.operation-buttons .el-button {
    width: 100%;
    margin-left: 0;
}

:deep(.operation-popover) {
    padding: 12px;
}
</style>